package com.vhall.component.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;

/**
 * @author skeleton
 * @since 2020/8/17
 **/
@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return (Jackson2ObjectMapperBuilder builder) -> {

            String dateFormatPattern = "yyyy-MM-dd HH:mm:ss";
            DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(dateFormatPattern);

            builder.failOnUnknownProperties(false)
                    // java8日期序列化/反序列化
                    .deserializers(new LocalDateTimeDeserializer(dateFormat))
                    .serializers(new LocalDateTimeSerializer(dateFormat))
                    // Date序列化/反序列化
                    .simpleDateFormat(dateFormatPattern)
                    // BigDecimal的序列化
                    .serializerByType(BigDecimal.class, ToStringSerializer.instance);
        };
    }

}
